#include "StdAfx.h"
#include "DataStore.h"

using namespace std;
DataStore::DataStore(void)
{
	current=-1;
	samplingRate=-1;
	refType=-1;
	int i=-1;
	refChannel[0]=0;
	refChannel[1]=0;
	refChannel[2]=0;
}

DataStore::~DataStore(void)
{
}

const Channel& DataStore::GetChannel(int n)
{
	//TODO: insert return statement here
	return data[n];
}

int DataStore::AddChannel(int eid)
{
	data.push_back(Channel(eid));
	switch(eid){
		case A1:
			refChannel[0]=&data[data.size()-1];break;
		case A2:
			refChannel[1]=&data[data.size()-1];break;
		case CZ:
			refChannel[2]=&data[data.size()-1];break;
		default:
			break;
	}
	current++;
	return data.size();
}

int DataStore::EndChannel(void)
{
	return data[current].data.size();
}

void DataStore::AddData2Channel(double d)
{
	data[current].data.push_back(d);
}

void DataStore::CleanAll(void)
{
	data.clear();
	current=-1;
	samplingRate=-1;
	refType=-1;
}

int DataStore::GetChannelCount(void)
{
	return data.size();
}

void DataStore::SetChannelName(LPCTSTR name)
{
	wcscpy(data[current].electrode.name,name);
}

void DataStore::SetRef(int refType)
{
	/*int i=0;
	if(refChannel[0]==0 || refChannel[1]==0 || refChannel[2]==0)
	{
	   refChannel[0]=&data[(i=GetElectrode(A1))==-1? 0:i];
	   refChannel[1]=&data[(i=GetElectrode(A2))==-1? 0:i];
	   refChannel[2]=&data[(i=GetElectrode(CZ))==-1? 0:i];
	}
	if(refType==0 && refChannel[0]!=0 && refChannel[1]!=0)
	  {  
		  this->refType=refType;
	      return true;
	  }
	else if(refType==1 && refChannel[3]!=0)
	  {  
		  this->refType=refType;
		  return true;
	  }
	  else return false;
		//Its host in CWaveAnalysisCtrl shall invoke UpdateEverthing()*/
	this->refType=refType;	//Its host in CWaveAnalysisCtrl shall invoke UpdateEverthing()
}

// Get the index of the channel from a given electrodeID. Return -1 if the that electrode is not available.
int DataStore::GetElectrode(int electrodeID)
{
	for(int i=0;i<GetChannelCount();i++)
	{  
		if(GetChannel(i).electrode.electrodeID==electrodeID)
		   return i;
	}
	return -1;
}

bool DataStore::GetRefData(int ch, UINT index, double &refData)
{
	if(ch>=data.size())
		return false;
	if(refType==-1)
		refData=data[ch].data[index];
		return false;
	if(refType==0)
	{	
		refData=data[ch].data[index]-(refChannel[0]->data[index]+refChannel[1]->data[index])/2;
		return true;
	}
	if(refType==1)
	{	
		refData=data[ch].data[index]-refChannel[3]->data[index];
		return true;
	}
	else return false;
}

Channel* DataStore::GetChannelByEID(unsigned int eid)
{
	//TODO: insert return statement here
	for(int i=0;i<data.size();i++){
		if(data[i].electrodeID==eid)
			return  &data[i];
	}
	return 0;
}
